# -*- coding: utf-8 -*-
"""
@Time ： 2021/11/16 11:23
@Auth ： Jolg
@File ：pyt.py
@IDE ：PyCharm
"""

import sys
import pymysql
from conf import logger
from utils.tool import Dict2Obj

class Mysql:
    def __init__(self,**db):
        self.host = db['host']
        self.port = db['port']
        self.db = db['dbname']
        self.username = db['username']
        self.password = db['password']
        self.chartset = 'utf8'
    def _getConnect(self):
        try:
            conn = pymysql.connect(host=self.host,
                                        user=self.username,
                                        passwd=self.password,
                                        db=self.db,
                                        port=self.port,
                                        charset=self.chartset)
            return conn
        except Exception as e:
            logger.error(f'连接数据库出错：{e}')

    def duexe(self, sql, Params={}):
        conn=self._getConnect()
        cursor = conn.cursor()
        try:
            cursor.execute(sql, Params)
            conn.commit()
        except Exception as e:
            logger.error(f'sql执行出错：{e}')
            logger.error(f'{sql}==={Params}')
        cursor.close()
        conn.close()

    def query(self, sql, nameParams={}):
        conn = self._getConnect()
        cursor = conn.cursor()
        try:
            cursor.execute(sql, nameParams)
            rows = cursor.fetchall()
        except Exception as e:
            logger.warning('sql执行出错：', e)
        cursor.close()
        conn.close()
        return rows

    def querydict(self, sql, nameParams={}):
        conn=self._getConnect()
        cursor = conn.cursor()
        try:
            cursor.execute(sql, nameParams)
            sus=cursor.fetchall()
            col_names = [desc[0] for desc in cursor.description]
            resoult = []
            for row in sus:
                objDict = {}
                for index, value in enumerate(row):
                    objDict[col_names[index]] = value
                resoult.append(objDict)
        except:
            resoult = []
        cursor.close()
        conn.close()
        return resoult
    def querypagedict(self, page, sql, nameParams={}):
        parm=nameParams
        startrow = (page.PAGEINDEX - 1) * page.PAGESIZE
        pagesql=f'''{sql} limit {startrow},{page.PAGESIZE}'''
        # logger.info((self.pagesql, nameParams))
        resoult = self.querydict(pagesql, parm)
        return resoult
    def queryobj(self, sql, nameParams={}):
        conn=self._getConnect()
        cursor = conn.cursor()
        try:
            cursor.execute(sql, nameParams)
            sus=cursor.fetchall()
            col_names = [desc[0] for desc in cursor.description]
            resoult = []
            for row in sus:
                objDict = {}
                for index, value in enumerate(row):
                    objDict[col_names[index]] = value
                resoult.append(Dict2Obj(objDict))
        except:
            resoult = []
        cursor.close()
        conn.close()
        return resoult

async def paging(PAGEINDEX: int=1 ,PAGESIZE: int = 10):
    page = {'PAGEINDEX':PAGEINDEX,'PAGESIZE':PAGESIZE}
    return page
class Page:
    def __init__(self,PAGEINDEX: int=1 ,PAGESIZE: int = 10):
        self.PAGEINDEX=PAGEINDEX
        self.PAGESIZE=PAGESIZE

if __name__ == '__main__':
    db=Mysql(**config.MYDB)
    fromids=[1,2,3]
    sql='''select * from fsuser where id = %s and username=%s'''
    ids = f'''({",".join(map(str, fromids))})'''
    logger.info(ids)
    p = db.querydict(sql,(1,'admin'))
    print(p)
    # sql='select * from tab'
    # print(db.persql(sql))
    # print(db.dictpesql(sql))